package com.nuc.wxh.vaccine_appointment.base.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.nuc.wxh.vaccine_appointment.base.exception.VaccineException;
import com.nuc.wxh.vaccine_appointment.base.result.ResultCodeEnum;
import com.nuc.wxh.vaccine_appointment.base.util.MD5;
import com.nuc.wxh.vaccine_appointment.vaccines.entity.AdminDoctor;
import com.nuc.wxh.vaccine_appointment.vaccines.service.AdminDoctorService;

import java.util.ArrayList;
import java.util.List;

public class DoctorListener extends AnalysisEventListener<AdminDoctor> {
    public AdminDoctorService adminDoctorService;
    public String id;

    public DoctorListener(AdminDoctorService adminDoctorService,String id) {
        this.adminDoctorService = adminDoctorService;
        this.id=id;
    }

    public DoctorListener() {
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<AdminDoctor> list = new ArrayList<AdminDoctor>();


    /**
     * 每解析一条数据都会来调用这个方法
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(AdminDoctor data, AnalysisContext context) {
        if (data == null) {
            throw new VaccineException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
        }
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    /**
     * 每个sheet的所有数据解析完成了 都会来调用这个方法
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();

    }


    /**
     * 将读取到的数据存储到数据库
     */
    private void saveData() {

        for(AdminDoctor a:list){
            a.setPassword(MD5.encrypt(a.getPassword()));
            a.setHospitalId(id);
        }
        //存储到数据库
        try {
            adminDoctorService.saveBatch(list);
        } catch (Exception e) {
            throw new VaccineException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
        }


    }

}
